//
//  RCTLaunchView.m
//  leosmart
//
//  Created by cc on 2025/5/20.
//

#import "RCTLaunchView.h"
#import "React/RCTUIManager.h"
#import "Utils.h"
#import <React/RCTBridge.h>
#import <React/RCTRootView.h>
// 导入 Swift 类
#import "leosmart-Swift.h"

@implementation NativeLaunchManager
RCT_EXPORT_MODULE()

- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:(const facebook::react::ObjCTurboModule::InitParams &)params {
  return std::make_shared<facebook::react::NativeLaunchManagerSpecJSI>(params);
}
- (RCTRootView *)findRootView {
  for (UIWindow *window in UIApplication.sharedApplication.windows) {
    for (UIView *subview in window.subviews) {
      if ([subview isKindOfClass:[RCTRootView class]]) {
        return (RCTRootView *)subview;
      }
    }
  }
  return nil;
}

-(void)show:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject{
  dispatch_async(dispatch_get_main_queue(), ^{
      // 获取根视图控制器
      UIViewController *rootVC = [Utils getRootVC];
      UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
      
      // 移除已存在的启动页面
      UIView *existingLaunchView = [keyWindow viewWithTag:9999];
      if (existingLaunchView) {
          [existingLaunchView removeFromSuperview];
      }
      
      // 创建新的启动页面
      LaunchViewController *launchVC = [[LaunchViewController alloc] init];
      launchVC.view.frame = keyWindow.bounds;
      launchVC.view.tag = 9999;
      launchVC.view.alpha = 0; // 初始透明
      
      // 添加到窗口
      [keyWindow addSubview:launchVC.view];
      
      // 设置动画完成回调
      launchVC.onAnimationComplete = ^{
          // 动画完成后可以在这里添加额外的逻辑
          resolve(@(YES));
      };
      
      // 淡入动画
      [UIView animateWithDuration:0.3 animations:^{
          launchVC.view.alpha = 1;
      }];
      
      // 禁用根视图的用户交互
      rootVC.view.userInteractionEnabled = NO;
  });
}

- (void)hide:(nonnull NSString *)theme resolve:(nonnull RCTPromiseResolveBlock)resolve reject:(nonnull RCTPromiseRejectBlock)reject { 
  dispatch_async(dispatch_get_main_queue(), ^{
    // 正确的 Objective-C block
    UIViewController *rootVC = [Utils getRootVC];
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    UIView *launchView = [keyWindow viewWithTag:9999];
    if (launchView && rootVC.view) {
      [UIView animateWithDuration:0.5 animations:^{
        launchView.alpha = 0;
      } completion:^(BOOL finished) {
        [launchView removeFromSuperview];
        rootVC.view.userInteractionEnabled = YES;
        resolve(@(YES));
      }];
    }
    else {
      resolve(@(NO));
    }
  });
}


@end
